/**
 * This program is free software but WITHOUT ANY WARRANTY OR CONDITIONS OF ANY KIND.
 *
 * Copyright (C) 2008-2012 www.pretty-tools.com
 */

/**
 * Check for update of predefined rules.
 *
 * @author Alexander Kozlov
 */
var wsshRulesUpdateManager = {
    logger: yrprxFactory.createLogger("wsshRulesUpdateManager")
};

wsshRulesUpdateManager.checkForSubscriptionUpdate = function(subscriptionName)
{
    try
    {
        if (!subscriptionName)
            throw "Subscription name is empty";

        if (!this.subscriptions)
            this.subscriptions = wsshSubscriptionSerializer.load();

        var subscription = yrprxAlgorithm.findInArray(this.subscriptions, "name", subscriptionName);
        if (!subscription)
        {
            subscription = new wsshSubscription(subscriptionName);
            subscription.url = wsshConfig.urlSubscriptions + subscriptionName + ".xml";
        }

        var curDate = new Date();
        var curTime = curDate.getTime();
        var updateInterval = 1000 * 60 * wsshConfig.updateInterval; // convert to ms

        if ((curTime - subscription.updateTimeStamp) < updateInterval)
            return;

        // need to update subscription
        this.logger.debug("checkForSubscriptionUpdate: need to update subscription");
        // change timestamp to prevent updates
        subscription.updateTimeStamp = curTime;

        this.updateSubscription(subscription);
    }
    catch(ex)
    {
        if (this.logger.enabled) this.logger.error("checkForSubscriptionUpdate: Exception: " + ex);
    }
}

wsshRulesUpdateManager.checkForPredefinedRulesUpdate = function()
{
    try
    {
        if (!wsshConfig.updatePredefinedRules)
            return;

        if (!wsshWebProfileSerializer.profileExists(wsshWebProfileSerializer.getPredefinedProfile()))
        {
            wsshConfig.updateTimeStamp = "";
            wsshConfig.predefinedRulesLastModified = "";
        }

        var updateTimeStamp = yrprxUtil.convertStringToTime(wsshConfig.updateTimeStamp);
        if (this.logger.enabled) this.logger.debug("checkForPredefinedRulesUpdate: updateTimeStamp=" + new Date(updateTimeStamp));

        var curDate = new Date();
        var curTime = curDate.getTime();
        var updateInterval = 1000 * 60 * wsshConfig.updateInterval; // convert to ms

        if ((curTime - updateTimeStamp) < updateInterval)
            return;

        this.logger.debug("checkForPredefinedRulesUpdate: need to update predefined rules");
        // change timestamp to prevent updates
        wsshConfig.updateTimeStamp = curDate.toString();

        setTimeout(function() {
                wsshRulesUpdateManager.updatePredefinedRules();
        }, wsshConfig.waitBeforeUpdate);
    }
    catch(ex)
    {
        if (this.logger.enabled) this.logger.error("checkForPredefinedRulesUpdate: Exception: " + ex);
    }
}

wsshRulesUpdateManager.updatePredefinedRules = function()
{
    try
    {
        this.logger.debug("updatePredefinedRules: updating predefined rules");
        wsshRulesImportManager.loadProfileFromURLAsync(wsshConfig.urlPredefinedRules, function (items, lastModified){
            if (!items || !items.length)
                return;

            //TODO: currently javascript in pre-defined rules is not supported
            wsshRulesImportManager.disableJavaScript(items);

            wsshWebProfileSerializer.savePredefinedProfile(items);
            if (lastModified) wsshConfig.predefinedRulesLastModified = lastModified;
            // notify observers
            yrprxObserverServiceHelper.notifyObservers(null, WEBSLIDESHOW_UPDATE_RULES_EVENT, null);
        }, wsshConfig.predefinedRulesLastModified);
    }
    catch(ex)
    {
        if (this.logger.enabled) this.logger.error("updatePredefinedRules: Exception: " + ex);
    }
}

wsshRulesUpdateManager.updateSubscription = function(subscription)
{
    try
    {
        if (!subscription || !subscription.url)
            throw "Cannot get subscription url!";

        if (this.logger.enabled) this.logger.debug("updateSubscription: updating subscription: " + subscription.name);
        wsshRulesImportManager.loadProfileFromURLAsync(subscription.url, function (items, lastModified){

            if (lastModified) subscription.lastModified = lastModified;

            // reload because of multiple instances... TODO: move to XPCOM
            wsshRulesUpdateManager.subscriptions = wsshSubscriptionSerializer.load();
            var idx = yrprxAlgorithm.findIndex(wsshRulesUpdateManager.subscriptions, "name", subscription.name);
            if (idx == -1)
                wsshRulesUpdateManager.subscriptions.push(subscription);
            else
                wsshRulesUpdateManager.subscriptions[idx] = subscription;
            wsshSubscriptionSerializer.save(wsshRulesUpdateManager.subscriptions);

            if (!items || !items.length)
                return; // nothing to update

            //TODO: currently javascript in subscriptions is not supported
            wsshRulesImportManager.disableJavaScript(items);

            wsshWebProfileSerializer.saveProfile(subscription.name, items);
            // notify observers
            yrprxObserverServiceHelper.notifyObservers(null, WEBSLIDESHOW_UPDATE_RULES_EVENT, null);
        }, subscription.lastModified);
    }
    catch(ex)
    {
        if (this.logger.enabled) this.logger.error("updateSubscription: Exception: " + ex);
    }
}
